const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    routerPath: String,
    item: {
      type: Object
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleToCart(e) {
      console.log('e:', e.currentTarget.dataset.item)
      const item = e.currentTarget.dataset.item
      // 数组去重判断
      // 1. 查找 看他重复没有
      const goods = app.globalData.cartList.find(v => v.id === item.id)
      // 2. 重复 改变数量
      if (goods) {
        goods.num++;
      } else {
        // 3. 不重复 push
        app.globalData.cartList.push(item)
      }
      wx.showToast({
        title: '加入成功',
        mask: true
      })
      // 同步存储
      // wx.setStorageSync('cartList', JSON.stringify(app.globalData.cartList))
      // console.log('app:', app.globalData.cartList)
    },
    // +
    handleAdd(e) {
      const item = e.currentTarget.dataset.item
      const goods = app.globalData.cartList.find(v => v.id === item.id)
      goods.num++;
      // wx.setStorageSync('cartList', JSON.stringify(app.globalData.cartList))

      this.triggerEvent('toParentAdd')
    },
    // -
    async handleReduce(e) {
      const item = e.currentTarget.dataset.item
      const goods = app.globalData.cartList.find(v => v.id === item.id)
      try {
        if (goods.num <= 1) {
          const res = await wx.showModal({ content: '已经最后一个了，确定删除吗?', })
          if (res.confirm) {
            // 删除
            const removeIndex = app.globalData.cartList.findIndex(v => v.id === item.id)
            app.globalData.cartList.splice(removeIndex, 1)
            // wx.setStorageSync('cartList', JSON.stringify(app.globalData.cartList))
            this.triggerEvent('toParentReduce')
          }
          return;
        }
        goods.num--;
        // wx.setStorageSync('cartList', JSON.stringify(app.globalData.cartList))
        this.triggerEvent('toParentReduce')
      } catch (error) {
        wx.showToast({
          title: error,
        })
      }
    }
  }
})
